package com.chengqj.userserverprovider.service.impl;

import com.chengqj.user.server.dto.*;
import com.chengqj.user.server.service.IUserService;
import com.chengqj.userserverprovider.constants.ResponseCodeEnum;
import com.chengqj.userserverprovider.dao.entity.UmUser;
import com.chengqj.userserverprovider.dao.mapper.UmUserMapper;
import com.chengqj.userserverprovider.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UmUserMapper umUserMapper;
    @Override
    public UserRegisterResponse register(UserRegisterRequest userRegisterRequest) {
        UmUser user = new UmUser();
        user.setUserName(userRegisterRequest.getUserName());
        user.setPassword(userRegisterRequest.getPassword());
        int result = umUserMapper.insert(user);
        UserRegisterResponse response = new UserRegisterResponse();
        if (result==1){
            response.setCode(ResponseCodeEnum.SUCCESS.getCode());
            response.setMsg(ResponseCodeEnum.SUCCESS.getMsg());
        }else{
            response.setCode(ResponseCodeEnum.ERROR.getCode());
            response.setMsg(ResponseCodeEnum.ERROR.getMsg());
        }
        return response;
    }

    @Override
    public UserLoginResponse login(UserLoginRequest userLoginRequest) {
        UserLoginResponse response = new UserLoginResponse();
        UmUser umUser = umUserMapper.selectByNameAndPassword(userLoginRequest.getUserName(),userLoginRequest.getPassword());
        if (umUser!=null){
            Map<String,Object> map=new HashMap<>();
            map.put("username",umUser.getUserName());
            map.put("exp",new Date(System.currentTimeMillis()+30*60*1000));
            String jwt = JwtUtil.generatorToken(map);
            response.setToken(jwt);
            response.setCode(ResponseCodeEnum.SUCCESS.getCode());
            response.setMsg(ResponseCodeEnum.SUCCESS.getMsg());
        }else{
            response.setCode(ResponseCodeEnum.ERROR.getCode());
            response.setMsg(ResponseCodeEnum.ERROR.getMsg());
        }
        return response;
    }

    @Override
    public CheckAuthResponse checkAuth(CheckAuthRequest checkAuthRequest) {
        CheckAuthResponse response = new CheckAuthResponse();
        Claims chaim = JwtUtil.phaseToken(checkAuthRequest.getToken());
        if (chaim==null){
            response.setCode(ResponseCodeEnum.TOKEN_ERROR.getCode());
            response.setMsg(ResponseCodeEnum.TOKEN_ERROR.getMsg());
        }else{
            response.setUserName(chaim.get("username").toString());
            response.setCode(ResponseCodeEnum.SUCCESS.getCode());
            response.setMsg(ResponseCodeEnum.SUCCESS.getMsg());
        }
        return response;
    }
}
